package org.vison.wonfu.framework.test.admin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.vison.framework.doc.annotation.ApiCategory;
import org.vison.framework.doc.annotation.ApiMeta;
import org.vison.wonfu.framework.BaseRes;
import org.vison.wonfu.framework.test.admin.controller.req.LoginReq;
import org.vison.wonfu.framework.test.admin.controller.res.LoginInfo;
import org.vison.wonfu.framework.test.admin.controller.res.LoginRes;
import org.vison.wonfu.framework.test.admin.dao.entity.AdminPO;
import org.vison.wonfu.framework.test.admin.dao.AdminDao;
import org.vison.wonfu.framework.test.admin.controller.req.AdminAddReq;
import org.vison.wonfu.framework.test.admin.controller.req.AdminUpdateReq;
import org.vison.wonfu.framework.test.admin.controller.res.AdminDetailRes;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * 管理员控制器，提供管理员相关的REST接口
 */
@Slf4j
@RestController
@ApiCategory(categoryName = "管理员模块")
@RequestMapping("/api/admin")
public class AdminController {

    @Resource
    private AdminDao adminDao;

    /**
     * 管理员登录接口
     * @param req 登录请求参数
     * @return 登录结果，包含token
     */
    @ApiMeta(name = "管理员登录", description = "管理员登录接口", docLinks = {
            @ApiMeta.DocLink(url = "https://example.com/admin-login", title = "管理员登录接口文档"),
            @ApiMeta.DocLink(url = "https://example.com/admin-login-2", title = "v2.10需求文档修改登录逻辑")
    })
    @PostMapping("/login")
    public BaseRes<LoginRes> login(@RequestBody LoginReq req) {
        log.info("admin login request: {}", req.getUsername());
        
        // 验证用户名密码
        AdminPO admin = adminDao.queryOneByUsername(req.getUsername());
        if (admin == null || !"password".equals(req.getPassword())) {
            BaseRes<LoginRes> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("用户名或密码错误");
            return res;
        }
        
        // 生成token
        LoginRes res = new LoginRes();
        res.setToken(UUID.randomUUID().toString());
        return BaseRes.success(res);
    }
    
    /**
     * 获取当前登录用户信息
     * @return 用户信息
     */
    @PostMapping("/info")
    public BaseRes<LoginInfo> loginInfo(){
        LoginInfo info = new LoginInfo();
        info.setName("admin");
        info.setAvatar("https://example.com/avatar.png");
        info.setJob("管理员");
        info.setOrganization("wonfu-framework");
        info.setLocation("北京");
        info.setEmail("admin@example.com");
        info.setIntroduction("系统管理员");
        info.setRole(LoginInfo.RoleType.ADMIN);
        return BaseRes.success(info);
    }

    /**
     * 获取管理员列表（分页）
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return 管理员列表
     */
    @GetMapping("/list")
    public BaseRes<PageInfo<AdminPO>> list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<AdminPO> adminPOList = adminDao.findList();
        PageInfo<AdminPO> info = new PageInfo<>(adminPOList);
        return BaseRes.success(info);
    }
    
    /**
     * 获取管理员详情
     * @param id 管理员ID
     * @return 管理员详情
     */
    @GetMapping("/detail/{id}")
    public BaseRes<AdminDetailRes> detail(@PathVariable Long id) {
        AdminPO admin = adminDao.findOne(id.intValue());
        if (admin == null) {
            BaseRes<AdminDetailRes> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("管理员不存在");
            return res;
        }
        
        AdminDetailRes detail = new AdminDetailRes();
        detail.setId(admin.getId());
        detail.setUsername(admin.getUsername());
        detail.setEmail(admin.getEmail());
        detail.setCreateTime(admin.getCreateTime());
        detail.setUpdateTime(admin.getUpdateTime());
        
        return BaseRes.success(detail);
    }
    
    /**
     * 添加管理员
     * @param req 添加请求参数
     * @return 添加结果
     */
    @PostMapping("/add")
    public BaseRes<Long> add(@RequestBody AdminAddReq req) {
        // 检查用户名是否已存在
        AdminPO existing = adminDao.queryOneByUsername(req.getUsername());
        if (existing != null) {
            BaseRes<Long> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("用户名已存在");
            return res;
        }
        
        // 创建新管理员
        AdminPO admin = new AdminPO();
        admin.setUsername(req.getUsername());
        admin.setPassword(req.getPassword()); // 实际项目中应该加密存储
        admin.setEmail(req.getEmail());
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdateTime(LocalDateTime.now());
        
        boolean result = adminDao.insert(admin);
        if (result) {
            return BaseRes.success(admin.getId());
        } else {
            BaseRes<Long> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("添加失败");
            return res;
        }
    }
    
    /**
     * 更新管理员信息
     * @param req 更新请求参数
     * @return 更新结果
     */
    @PostMapping("/update")
    public BaseRes<Boolean> update(@RequestBody AdminUpdateReq req) {
        AdminPO admin = adminDao.findOne(req.getId());
        if (admin == null) {
            BaseRes<Boolean> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("管理员不存在");
            return res;
        }
        
        // 更新信息
        if (req.getUsername() != null) {
            admin.setUsername(req.getUsername());
        }
        if (req.getPassword() != null) {
            admin.setPassword(req.getPassword()); // 实际项目中应该加密存储
        }
        if (req.getEmail() != null) {
            admin.setEmail(req.getEmail());
        }
        admin.setUpdateTime(LocalDateTime.now());
        
        boolean result = adminDao.updateAdmin(admin);
        return BaseRes.success(result);
    }
    
    /**
     * 删除管理员
     * @param id 管理员ID
     * @return 删除结果
     */
    @PostMapping("/delete")
    public BaseRes<Boolean> delete(@RequestParam Long id) {
        AdminPO admin = adminDao.findOne(id.intValue());
        if (admin == null) {
            BaseRes<Boolean> res = new BaseRes<>();
            res.setRet(1);
            res.setMsg("管理员不存在");
            return res;
        }
        
        // 软删除
        admin.setDeleted(1);
        admin.setUpdateTime(LocalDateTime.now());
        
        boolean result = adminDao.updateAdmin(admin);
        return BaseRes.success(result);
    }
}